document.addEventListener('DOMContentLoaded', () => {
    // 游戏配置
    const config = {
        // 难度配置
        difficulties: {
            easy: {
                gridRows: 15,
                gridCols: 15,
                thiefDelay: 600,
                randomMoveProbability: 0
            },
            medium: {
                gridRows: 13,
                gridCols: 13,
                thiefDelay: 400, 
                randomMoveProbability: 0.15
            },
            hard: {
                gridRows: 11,
                gridCols: 11,
                thiefDelay: 300,
                randomMoveProbability: 0.3
            }
        },
        currentDifficulty: 'easy',
        thiefChar: '👤',
        barrierChar: '🚧',
        mobileScale: 0.7 // 移动设备上网格的缩放比例
    };

    // 游戏状态
    let gameState = {
        started: false,
        grid: [],
        thiefPosition: null,
        barriers: [],
        gameOver: false,
        barrierCount: 0,    // 记录放置的障碍物数量
        moveRatio: {        // 不同难度下，玩家放置几个障碍物小偷才移动一次
            easy: 2,        // 简单模式：放置2个障碍物，小偷移动1次
            medium: 1.5,    // 中等模式：放置3个障碍物，小偷移动2次
            hard: 1         // 困难模式：放置1个障碍物，小偷移动1次
        }
    };

    // 获取DOM元素
    const gameGrid = document.getElementById('game-grid');
    const startButton = document.getElementById('start-button');
    const resetButton = document.getElementById('reset-button');
    const playAgainButton = document.getElementById('play-again');
    const resultModal = document.getElementById('result-modal');
    const resultTitle = document.getElementById('result-title');
    const resultMessage = document.getElementById('result-message');
    const messageElement = document.getElementById('message');
    const easyButton = document.getElementById('easy-button');
    const mediumButton = document.getElementById('medium-button');
    const hardButton = document.getElementById('hard-button');

    // 检测是否为移动设备
    const isMobile = window.innerWidth <= 600;

    // 获取当前难度设置
    function getDifficultySettings() {
        return config.difficulties[config.currentDifficulty];
    }

    // 设置难度
    function setDifficulty(difficulty) {
        // 如果难度没有变化，不做处理
        if (config.currentDifficulty === difficulty) return;
        
        config.currentDifficulty = difficulty;
        
        // 更新按钮样式
        [easyButton, mediumButton, hardButton].forEach(btn => {
            btn.classList.remove('active');
        });
        
        if (difficulty === 'easy') easyButton.classList.add('active');
        else if (difficulty === 'medium') mediumButton.classList.add('active');
        else if (difficulty === 'hard') hardButton.classList.add('active');
        
        // 重新初始化游戏，确保网格大小更新
        resetGame();
        
        // 提示玩家难度已更改
        updateMessage(`难度已设置为${difficulty === 'easy' ? '简单' : difficulty === 'medium' ? '中等' : '困难'}`);
    }

    // 初始化游戏
    function initGame() {
        const settings = getDifficultySettings();
        let gridRows = settings.gridRows;
        let gridCols = settings.gridCols;
        
        // 移动设备上减少格子数量
        if (isMobile) {
            gridRows = Math.floor(gridRows * config.mobileScale);
            gridCols = Math.floor(gridCols * config.mobileScale);
        }
        
        console.log(`初始化游戏，难度: ${config.currentDifficulty}, 网格大小: ${gridRows}x${gridCols}`);
        
        gameState = {
            started: false,
            grid: [],
            thiefPosition: null,
            barriers: [],
            gameOver: false,
            barrierCount: 0,    // 记录放置的障碍物数量
            moveRatio: {        // 不同难度下，玩家放置几个障碍物小偷才移动一次
                easy: 2,        // 简单模式：放置2个障碍物，小偷移动1次
                medium: 1.5,    // 中等模式：放置3个障碍物，小偷移动2次
                hard: 1         // 困难模式：放置1个障碍物，小偷移动1次
            }
        };

        gameGrid.innerHTML = '';
        
        // 创建六边形网格
        for (let row = 0; row < gridRows; row++) {
            const hexRow = document.createElement('div');
            hexRow.classList.add('hex-row');
            gameGrid.appendChild(hexRow);
            
            gameState.grid[row] = [];
            
            for (let col = 0; col < gridCols; col++) {
                const cell = document.createElement('div');
                cell.classList.add('cell');
                
                // 标记边缘格子
                if (row === 0 || col === 0 || row === gridRows - 1 || col === gridCols - 1) {
                    cell.classList.add('edge');
                }
                
                cell.dataset.row = row;
                cell.dataset.col = col;
                cell.addEventListener('click', () => handleCellClick(row, col));
                
                hexRow.appendChild(cell);
                gameState.grid[row][col] = {
                    type: 'empty',
                    element: cell
                };
            }
        }

        updateMessage('点击"开始游戏"放置小偷');
        startButton.disabled = false;
    }

    // 开始游戏
    function startGame() {
        if (gameState.started) return;
        
        const settings = getDifficultySettings();
        let gridRows = settings.gridRows;
        let gridCols = settings.gridCols;
        
        // 移动设备上减少格子数量
        if (isMobile) {
            gridRows = Math.floor(gridRows * config.mobileScale);
            gridCols = Math.floor(gridCols * config.mobileScale);
        }
        
        // 将小偷固定放置在网格中心点
        const thiefRow = Math.floor(gridRows / 2);
        const thiefCol = Math.floor(gridCols / 2);
        
        placeThief(thiefRow, thiefCol);
        gameState.started = true;
        startButton.disabled = true;
        
        // 提示玩家最佳围堵策略
        let tip = '提示：尝试先在小偷周围形成一个包围圈再慢慢缩小！';
        if (config.currentDifficulty === 'easy') {
            tip = '提示：从四个方向向小偷包围，形成一个封闭的圈！';
        } else if (config.currentDifficulty === 'medium') {
            tip = '提示：小偷可能会随机移动，多留一些备用的路障位置！';
        } else {
            tip = '提示：在关键路径上多放置路障，预测小偷可能的移动路线！';
        }
        updateMessage(tip);
        
        // 在简单模式下，高亮显示可能的包围策略
        if (config.currentDifficulty === 'easy') {
            setTimeout(highlightSuggestedMoves, 1000);
        }
    }

    // 高亮显示建议的移动
    function highlightSuggestedMoves() {
        if (!gameState.started || gameState.gameOver) return;
        
        const { row, col } = gameState.thiefPosition;
        const distance = 3; // 显示距离小偷3格的建议位置
        
        // 临时高亮一些建议的位置
        for (let r = Math.max(1, row - distance); r <= Math.min(gameState.grid.length - 2, row + distance); r++) {
            for (let c = Math.max(1, col - distance); c <= Math.min(gameState.grid[0].length - 2, col + distance); c++) {
                // 只高亮空格子
                if (gameState.grid[r][c].type === 'empty' && 
                    // 在小偷周围一定距离，形成一个圆环
                    Math.abs(r - row) + Math.abs(c - col) === distance) {
                    
                    const cell = gameState.grid[r][c].element;
                    cell.style.backgroundColor = '#aed6f1'; // 淡蓝色高亮
                    cell.style.boxShadow = '0 0 5px #3498db';
                    
                    // 2秒后恢复正常
                    setTimeout(() => {
                        if (gameState.grid[r][c].type === 'empty') {
                            cell.style.backgroundColor = '';
                            cell.style.boxShadow = '';
                        }
                    }, 2000);
                }
            }
        }
    }

    // 放置小偷
    function placeThief(row, col) {
        gameState.thiefPosition = { row, col };
        gameState.grid[row][col].type = 'thief';
        gameState.grid[row][col].element.classList.add('thief');
        gameState.grid[row][col].element.innerHTML = config.thiefChar;
    }

    // 移动小偷
    function moveThief() {
        // 使用广度优先搜索找到最近的出路
        const path = findPathToExit();
        const settings = getDifficultySettings();
        
        if (path.length > 0) {
            // 标记小偷将移动，添加过渡效果
            if (gameState.thiefPosition) {
                const oldCell = gameState.grid[gameState.thiefPosition.row][gameState.thiefPosition.col].element;
                oldCell.classList.add('moving');
            }
            
            // 移除旧位置的小偷
            const { row: oldRow, col: oldCol } = gameState.thiefPosition;
            gameState.grid[oldRow][oldCol].type = 'empty';
            gameState.grid[oldRow][oldCol].element.classList.remove('thief');
            gameState.grid[oldRow][oldCol].element.innerHTML = '';
            
            let newRow, newCol;
            
            // 降低难度：有一定概率小偷会停留在原地
            if (Math.random() < 0.15) {
                // 15%概率小偷停留原地一回合
                newRow = oldRow;
                newCol = oldCol;
                updateMessage('小偷迷路了，暂时停留在原地');
            }
            // 根据难度可能随机移动而不是最优路径
            else if (Math.random() < settings.randomMoveProbability) {
                // 随机选择一个可行的邻近格子
                const neighbors = getValidNeighbors(oldRow, oldCol);
                if (neighbors.length > 0) {
                    const randomNeighbor = neighbors[Math.floor(Math.random() * neighbors.length)];
                    newRow = randomNeighbor.row;
                    newCol = randomNeighbor.col;
                    updateMessage('小偷随机移动了一步');
                } else {
                    // 如果没有可行的邻近格子，使用最优路径的第一步（确保只走一格）
                    if (isAdjacent(oldRow, oldCol, path[0].row, path[0].col)) {
                        newRow = path[0].row;
                        newCol = path[0].col;
                    } else {
                        // 如果最优路径第一步不相邻，找到通向该方向的一个相邻格子
                        const neighbors = getValidNeighbors(oldRow, oldCol);
                        if (neighbors.length > 0) {
                            // 尝试找到最接近目标路径的邻居
                            let bestNeighbor = neighbors[0];
                            let minDistance = Infinity;
                            
                            for (const neighbor of neighbors) {
                                const distance = Math.abs(neighbor.row - path[0].row) + Math.abs(neighbor.col - path[0].col);
                                if (distance < minDistance) {
                                    minDistance = distance;
                                    bestNeighbor = neighbor;
                                }
                            }
                            
                            newRow = bestNeighbor.row;
                            newCol = bestNeighbor.col;
                        } else {
                            // 如果没有可行邻居，停留原地
                            newRow = oldRow;
                            newCol = oldCol;
                        }
                    }
                    updateMessage('小偷找到了最佳路径');
                }
            } else {
                // 确保只走最优路径的第一步（确保只走一格）
                if (path.length > 0) {
                    if (isAdjacent(oldRow, oldCol, path[0].row, path[0].col)) {
                        newRow = path[0].row;
                        newCol = path[0].col;
                    } else {
                        // 找到一个朝向最佳路径方向的相邻格子
                        const neighbors = getValidNeighbors(oldRow, oldCol);
                        if (neighbors.length > 0) {
                            // 尝试找到最接近目标路径的邻居
                            let bestNeighbor = neighbors[0];
                            let minDistance = Infinity;
                            
                            for (const neighbor of neighbors) {
                                const distance = Math.abs(neighbor.row - path[0].row) + Math.abs(neighbor.col - path[0].col);
                                if (distance < minDistance) {
                                    minDistance = distance;
                                    bestNeighbor = neighbor;
                                }
                            }
                            
                            newRow = bestNeighbor.row;
                            newCol = bestNeighbor.col;
                        } else {
                            // 如果没有可行邻居，停留原地
                            newRow = oldRow;
                            newCol = oldCol;
                        }
                    }
                    updateMessage('小偷正在寻找出路');
                } else {
                    // 无路可走，停留在原地
                    newRow = oldRow;
                    newCol = oldCol;
                    updateMessage('小偷找不到出路了');
                }
            }
            
            // 检查是否到达边缘
            const gridRows = gameState.grid.length;
            const gridCols = gameState.grid[0].length;
            
            if (newRow === 0 || newCol === 0 || newRow === gridRows - 1 || newCol === gridCols - 1) {
                gameOver(false);
                return;
            }
            
            // 平滑过渡：先短暂延迟，再放置小偷
            setTimeout(() => {
                placeThief(newRow, newCol);
                
                // 突出显示小偷的新位置
                const newCell = gameState.grid[newRow][newCol].element;
                newCell.classList.add('just-moved');
                
                setTimeout(() => {
                    newCell.classList.remove('just-moved');
                }, 500);
            }, 200);
        } else {
            // 如果找不到路径，玩家胜利
            gameOver(true);
        }
    }

    // 检查两个位置是否相邻
    function isAdjacent(row1, col1, row2, col2) {
        // 获取从位置1到其所有相邻位置
        const neighbors = getValidNeighbors(row1, col1);
        
        // 检查位置2是否在这些相邻位置中
        return neighbors.some(neighbor => neighbor.row === row2 && neighbor.col === col2);
    }

    // 获取合法的相邻格子
    function getValidNeighbors(row, col) {
        const neighbors = [];
        const gridRows = gameState.grid.length;
        const gridCols = gameState.grid[0].length;
        
        // 六边形网格中的相邻格子
        // 对于偶数行，相邻的列是: 左上、右上、左、右、左下、右下
        // 对于奇数行，相邻的列是: 左上、右上、左、右、左下、右下
        const directions = [
            { row: -1, col: row % 2 === 0 ? -1 : 0 },  // 左上
            { row: -1, col: row % 2 === 0 ? 0 : 1 },   // 右上
            { row: 0, col: -1 },                        // 左
            { row: 0, col: 1 },                         // 右
            { row: 1, col: row % 2 === 0 ? -1 : 0 },   // 左下
            { row: 1, col: row % 2 === 0 ? 0 : 1 }     // 右下
        ];
        
        for (const dir of directions) {
            const newRow = row + dir.row;
            const newCol = col + dir.col;
            
            // 检查是否在网格内且不是障碍
            if (newRow >= 0 && newRow < gridRows && 
                newCol >= 0 && newCol < gridCols && 
                gameState.grid[newRow][newCol].type !== 'barrier') {
                
                neighbors.push({ row: newRow, col: newCol });
            }
        }
        
        return neighbors;
    }

    // 使用BFS寻找到边缘的最短路径
    function findPathToExit() {
        const { row, col } = gameState.thiefPosition;
        const gridRows = gameState.grid.length;
        const gridCols = gameState.grid[0].length;
        
        const visited = Array(gridRows).fill().map(() => Array(gridCols).fill(false));
        const queue = [{ row, col, path: [] }];
        visited[row][col] = true;
        
        while (queue.length > 0) {
            const current = queue.shift();
            
            // 如果到达边缘
            if (current.row === 0 || current.col === 0 || 
                current.row === gridRows - 1 || current.col === gridCols - 1) {
                return current.path;
            }
            
            // 探索六边形网格的六个方向
            const neighbors = getValidNeighbors(current.row, current.col);
            
            for (const neighbor of neighbors) {
                if (!visited[neighbor.row][neighbor.col]) {
                    visited[neighbor.row][neighbor.col] = true;
                    const newPath = [...current.path, { row: neighbor.row, col: neighbor.col }];
                    queue.push({ row: neighbor.row, col: neighbor.col, path: newPath });
                }
            }
        }
        
        // 如果找不到路径
        return [];
    }

    // 处理单元格点击
    function handleCellClick(row, col) {
        if (!gameState.started || gameState.gameOver) return;
        
        // 不能点击已有内容的格子
        if (gameState.grid[row][col].type !== 'empty') return;
        
        // 放置障碍
        gameState.grid[row][col].type = 'barrier';
        gameState.grid[row][col].element.classList.add('barrier');
        gameState.grid[row][col].element.innerHTML = config.barrierChar;
        gameState.barriers.push({ row, col });
        
        // 增加障碍物计数
        gameState.barrierCount++;
        
        // 获取当前难度的移动比率
        const currentRatio = gameState.moveRatio[config.currentDifficulty];
        
        // 显示剩余步数提示
        const stepsNeeded = Math.ceil(currentRatio - (gameState.barrierCount % currentRatio));
        if (stepsNeeded > 0 && stepsNeeded < currentRatio) {
            updateMessage(`小偷将在你再放置${stepsNeeded}个障碍物后移动`);
        }
        
        // 判断是否应该移动小偷
        const shouldMove = Math.floor(gameState.barrierCount / currentRatio) > 
                         Math.floor((gameState.barrierCount - 1) / currentRatio);
        
        // 如果达到移动条件，小偷移动
        if (shouldMove) {
            const settings = getDifficultySettings();
            updateMessage('小偷正在思考路线...');
            
            // 添加动画效果，减少"瞬移"感
            setTimeout(() => {
                moveThief();
            }, settings.thiefDelay);
        }
    }

    // 游戏结束
    function gameOver(playerWins) {
        gameState.gameOver = true;
        
        if (playerWins) {
            resultTitle.textContent = '胜利！';
            resultTitle.className = 'win';
            resultMessage.textContent = '你成功围住了小偷！';
        } else {
            resultTitle.textContent = '失败！';
            resultTitle.className = 'lose';
            resultMessage.textContent = '小偷逃到了边缘！';
        }
        
        resultModal.classList.add('active');
    }

    // 更新消息
    function updateMessage(message) {
        messageElement.textContent = message;
    }

    // 重置游戏（修复再玩一次功能）
    function resetGame() {
        gameState = {
            started: false,
            grid: [],
            thiefPosition: null,
            barriers: [],
            gameOver: false,
            barrierCount: 0,    // 记录放置的障碍物数量
            moveRatio: {        // 不同难度下，玩家放置几个障碍物小偷才移动一次
                easy: 2,        // 简单模式：放置2个障碍物，小偷移动1次
                medium: 1.5,    // 中等模式：放置3个障碍物，小偷移动2次
                hard: 1         // 困难模式：放置1个障碍物，小偷移动1次
            }
        };
        
        // 重置开始按钮状态
        startButton.disabled = false;
        
        // 初始化游戏
        initGame();
    }

    // 绑定事件
    startButton.addEventListener('click', startGame);
    resetButton.addEventListener('click', resetGame);
    playAgainButton.addEventListener('click', () => {
        resultModal.classList.remove('active');
        resetGame();
    });
    
    // 难度按钮事件
    easyButton.addEventListener('click', () => setDifficulty('easy'));
    mediumButton.addEventListener('click', () => setDifficulty('medium'));
    hardButton.addEventListener('click', () => setDifficulty('hard'));

    // 窗口调整大小时重置游戏
    window.addEventListener('resize', () => {
        const newIsMobile = window.innerWidth <= 600;
        if (newIsMobile !== isMobile) {
            location.reload();  // 简单处理方式：刷新页面
        }
    });

    // 初始化游戏
    initGame();
});